var login = require('../../utils/login.js');
var setting = require('../../utils/settings.js');
var log = require('../../log.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    logo: "",
    mallName: "",
    backUrl: "",
    createUid: 0,
    couponTypeIds: '',
    staffid: 0,
    allianceid: 0,
    code: '',
    canIUseGetUserProfile: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.getInfo();
    let backUrl = '';
    if (options.query) {
      var query = JSON.parse(options.query);
      var s = "?"
      for (var key in query) {
        s += key + "=" + query[key] + "&";
      }
      s = s.substring(0, s.length - 1);
      backUrl = options.back + s;
    }
    if (options.id) {
      var s = "?id=" + options.id;
      backUrl = options.back + s;
    }
    if (options.pid) {
      var s = "?pid=" + options.pid;
      if (options.jump) {
        s = "?pid=" + options.pid + '&seltoid=' + options.seltoid + '&jump=1&saleUid=' + options.saleUid + '&name=' + options.name;
      }
      backUrl = options.back + s;
    } else {
      backUrl = options.back;
    }
    if (options.createUid) {
      let createUid = options.createUid;
      let couponTypeIds = options.couponTypeIds;
      backUrl = options.back;
      this.setData({
        createUid: createUid,
        couponTypeIds: couponTypeIds
      })
    }
    if (options.allianceId) {
      let staffid = options.staffid;
      let allianceid = options.allianceId;
      backUrl = options.back;
      this.setData({
        allianceid: allianceid,
        staffid: staffid
      })
    }
    if (options.isCreateStaff) {
      var s = "?isCreateStaff=" + options.isCreateStaff;
      backUrl = options.back + s;
    }
    if (options.isPlatform) {
      var s = "?isPlatform=" + options.isPlatform;
      backUrl = options.back + s;
    }
    if (backUrl.indexOf("/") == 0) {
      backUrl = backUrl;
    } else {
      backUrl = "/" + backUrl;
    }
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    this.setData({
      backUrl: decodeURIComponent(backUrl)
    })
    wx.setNavigationBarTitle({
      title: "微信授权登录"
    })
    let that = this;
    wx.login({
      success: function (res) {
        that.data.code = res.code;
      }
    })
  },
  getUserProfile: function () {
    let that = this;
    var iv = '';
    var encryptedData = '';
    var nickName = '';
    var avatar = '';
    
    wx.showLoading({title: '加载中',mask: true});
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用于完善会员资料', res);
        if (res.encryptedData) {
          iv = res.iv;
          encryptedData = res.encryptedData;
        } else {
          if (res.userInfo && res.userInfo.avatarUrl) {
            nickName = res.userInfo.nickName;
            avatar = res.userInfo.avatarUrl;
          }
          wx.getSystemInfo({
            success: (result) => {
              let infos = '授权微信头像昵称失败相关系统版本。SDKVersion:' + result.SDKVersion + ';手机型号：' + result.model + '；手机系统版本：' + result.system + ';微信版本：' + result.version
              log.info(infos);
            },
          })
        }
        // 下面开始调用注册接口
        wx.request({
          url: app.globalData.host + '/api/account/WxOpenRegister',
          data: {
            code: that.data.code,
            encryptedData: encryptedData,
            iv: iv,
            nickName: nickName,
            avatar: avatar,
            uid: app.globalData.userInfo.Uid,
            storeid: app.globalData.storeId,
            storeAppId: app.globalData.storeAppId
          }, // 设置请求的 参数
          method: 'POST',
          success: (ress) => {
            if (ress.data.Code == 0) {
              that.getUserInfoAgain(app.globalData.userInfo.Uid,()=>{
                wx.redirectTo({
                  url: that.data.backUrl
                })
              });
            } else {
              that.showModal( ress.data.Message);            
            }
          }
        })
      },
      fail: (err) => {
        that.showToast('用户拒绝授权');
      }
    })
  },

  //注册
  onGotUserInfo: function (e) {
    var that = this;
    var iv = e.detail.iv;
    var encryptedData = e.detail.encryptedData;
    // 下面开始调用注册接口
    wx.request({
      url: app.globalData.host + '/api/account/WxOpenRegister',
      data: {
        code: that.data.code,
        encryptedData: encryptedData,
        iv: iv,
        storeid: app.globalData.storeId,
        storeAppId: app.globalData.storeAppId
      }, // 设置请求的 参数
      method: 'POST',
      success: (res) => {
        if (res.data.Code == 0) {
          that.getUserInfoAgain(app.globalData.userInfo.Uid);
          if (that.data.createUid > 0) {
            that.getCouponsHolder();
          } else {
            wx.redirectTo({
              url: that.data.backUrl,
            })
          }
        } else {
          that.showModal('请在授权确认框点击允许按钮！');
        }
      }
    })
  },
  getUserInfoAgain: function(uid,callback) {
    wx.request({
      url: app.globalData.host + '/api/User/GetUserInfo?uid=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {
          var realUserInfo = res.data.Data.UserInfo
          app.globalData.userInfo = realUserInfo
        }
        if(callback){
          callback();
        }
      }
    })
  },

  // 取消登陆
  cancelLogin: function () {
    let url = this.data.backUrl;
    if (url.indexOf('isCreate') != -1) {
      url += '&isAgree=2'
    }
    wx.redirectTo({
      url: url,
    })
  },

  getInfo: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetInfo',
      data: {
        id: app.globalData.storeId
      },
      success: function (res) {
        if (res.data.Data.Logo) {
          var logoSrc = 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/logo/source/' + res.data.Data.Logo;
        } else {
          logoSrc = ''
        }
        that.setData({
          logo: logoSrc,
          mallName: res.data.Data.Name,
        })
      }
    })
  },
  // 一键领取优惠券(共享版)
  getCouponsHolder: function () {
    let that = this;
    let cardId = wx.getStorageSync('cardId');
    wx.showLoading({title: '正在领取',mask: true})
    wx.request({
      url: app.globalData.host + '/api/Coupon/AddUserPackage',
      data: {
        uid: app.globalData.userInfo.Uid,
        createUid: that.data.createUid,
        staffId: cardId,
        couponTypeIds: that.data.couponTypeIds
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          that.showToast('领取成功');
          setting.set_user_coupon_dialog_status(cardId, false);
        } else {
          that.showModal(res.data.Message);
        }
        wx.reLaunch({
          url: '/merchant/merchants/myCardCoupon/index',
        })
      }
    })
  },

  // 一键领取联盟券
  getAllianceCoupon: function () {
    wx.redirectTo({
      url: this.data.backUrl + '?allianceid=' + this.data.allianceid + '&id=' + this.data.staffid + '&showDialog=true',
    })
  },

  showModal: function(content){
    wx.showModal({
      title: '提示',
      content: content,
      showCancel: false
    })
  },
  showToast: function(title){
    wx.showToast({
      title: title,
      icon: 'none'
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  }
})